- Java Unit Testing
- A Simple Unit Test
- Assert Methods
- Matchers
- Testing for Exceptions
- Stub, Mock and Proxy Testing
- Subclass Mock Objects
- Mock Testing isn't Always Enough
- IO Testing
- Servlet Unit Testing
- Unit Testing with Dependency Injection Containers
- Database Unit Testing - Rollback Transactions
- Database Unit Testing - CRUD Testing
- Database Unit Testing - Test Data Creation
- Running Unit Tests With Ant
- Running Unit Tests With Maven
- Running Unit Tests Inside IntelliJ IDEA
- Code Coverage
- Design for Testability
- Test First Development
Database Unit Testing - Rollback Transactions
Jakob Jenkov |
If you are testing a component that uses a database, e.g. a DAO class, you may want to test that the component really inserts data into the database, updates it etc.
When testing if database components work correctly, you often have to insert a lot of data into the database, so the components have some data to work on. Unfortunately, this also means that you have to clean up all that data, when the unit test finishes, in order not to disturb other unit tests that setup data too.
A smart way to achieve this is by running the unit test inside a transaction. All data is inserted, read etc. inside the same transaction. When the unit test finishes, you can just rollback the transaction, and all the inserted data will be gone.
Here is a simple template showing you how to do this:
@Test
public void testIt() throws Exception {
Connection connection = getConnection();
connection.setAutoCommit(false); //begin transaction
MyDao myDao = new MyDaoImpl(connection);
try{
myDao.insertABC("1");
myDao.insertABC("2");
assertEquals("1", myDao.readABC("1"));
assertEquals("2", myDao.readABC("2"));
} finally {
connection.rollback();
connection.close();
}
}
It is possible that your persistence technology does not allow you to access the database connection directly. But, usually you can still control the underlying transaction, and thus start and rollback a transaction.
| Tweet | |
Jakob Jenkov | |









